package com.xiaojie.mongodb.service;

import com.mongodb.client.result.UpdateResult;
import com.xiaojie.mongodb.model.TestUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author 熟透的蜗牛
 * @version 1.0
 * @description: mongodb 正增删改查
 * @date 2023/1/6 0:03
 */
@Service
@Slf4j
public class TestUserServiceImpl implements TestUserService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<TestUser> listByPage(int page, int pageSize) {
        Query skip = new Query().skip((page - 1) * pageSize).limit(pageSize);
        return mongoTemplate.find(skip, TestUser.class);
    }

    @Override
    public void saveTestUser() {
        for (int i = 0; i < 1000; i++) {
            TestUser build = TestUser.builder().id(1000L + i)
                    .pin("admin")
                    .userName("admin")
                    .nickName("熟透的蜗牛")
                    .trueName("熟透的蜗牛")
                    .gender(1).mobile("15202205170").phone("110")
                    .email("whisper_snali@163.com")
                    .head("www.baidu.com")
                    .deptId(100000L)
                    .status(1)
                    .isDelete(0)
                    .postStatus(1).created("admin").updated("admin").createTime(new Date()).updateTime(new Date()).build();
            TestUser save = mongoTemplate.save(build);
        }

    }

    @Override
    public void updateTestUser(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").lt(userId));
        query.addCriteria(Criteria.where("mobile").is("15202205170"));
        Update update = new Update().set("createTime", new Date()).set("updateTime", new Date());
        mongoTemplate.updateFirst(query, update, TestUser.class);
        UpdateResult updateResult = mongoTemplate.updateMulti(query, update, TestUser.class);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>{}", updateResult);
    }

    @Override
    public void removeByUserId(Long userId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(userId));
        mongoTemplate.remove(query, TestUser.class);
    }
}
